package com.duruikang.LeaveAPI.api;

import com.duruikang.LeaveAPI.common.http.ResponseResult;
import com.duruikang.LeaveAPI.common.http.StatusCode;
import com.duruikang.LeaveAPI.common.sercurity.utils.JwtTokenUtil;
import com.duruikang.LeaveAPI.form.LoginForm;
import com.duruikang.LeaveAPI.form.TokenForm;
import com.duruikang.LeaveAPI.service.impl.LoginServiceImpl;
import com.duruikang.LeaveAPI.service.impl.SecurityServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Drik
 * @date 2021-12-09 18:30
 */
@CrossOrigin
@RestController
@RequestMapping("/api")
public class LoginApi {
    /**
     * 服务层对象
     */
    @Autowired
    private LoginServiceImpl ser;

    /**
     * 安全验证服务层对象
     */
    @Autowired
    private SecurityServiceImpl securityService;

    /**
     * 封装token的工具类对象
     */
    @Autowired
    private JwtTokenUtil jwtUtil;

    /**
     * 根据用户输入的账户和密码，判断登陆成功与否，并返回相应状态码
     *
     * @param form
     * @return 登录结果信息
     */
    @PostMapping("/login")
    public ResponseResult<Map<String, String>> login(@RequestBody @Valid LoginForm form) {
        Map<String, String> map = ser.login(form.getUserName(), form.getPassword());
        if ("1".equals(map.get("res"))) {
            //判断用户的角色并返回不同的状态码，使前端返根据角色跳转页面
            String token = jwtUtil.createToken(map.get("account_id"));
            Map<String, String> res = new HashMap<>();
            res.put("authtoken", token);
            res.put("username", map.get("username"));
            securityService.registerToken(token);
            if("1".equals(map.get("account_role"))){
                return ResponseResult.getMessageResult(res, "A010", StatusCode.C200);
            }else{
                return ResponseResult.getMessageResult(res, "A011", StatusCode.C200);
            }
        } else if ("-1".equals(map.get("res"))) {
            return ResponseResult.getMessageResult(null, "A001");
        } else {
            return ResponseResult.getMessageResult(null, "A002");
        }
    }

    @PostMapping("/logout")
    public ResponseResult<Boolean>logout(@RequestBody @Valid TokenForm form){
        if(securityService.removeToken(form.getToken())==1){
            return ResponseResult.getSuccessResult(true);
        }else {
            return ResponseResult.getSuccessResult(false);
        }
    }
}
